package com.spzx.product.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.domain.Brand;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.api.domin.ProductSku;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.*;
import com.spzx.product.vo.CategoryVo;
import com.spzx.product.vo.IndexDataVo;
import com.spzx.product.vo.ItemVo;
import com.spzx.product.vo.ProductSkuVo;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: atguigu
 * @create: 2025-04-30 15:02
 */
@RestController
@RequestMapping("/channel")
public class ChannelController extends BrandController{

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductSkuService productSkuService;
    @Autowired
    private ProductDetailsService productDetailsService;


    @Operation(summary = "首页数据")
    @GetMapping("/index")
    public AjaxResult indexData() {
        //1.创建首页VO对象
        IndexDataVo vo = new IndexDataVo();
        //2.封装一级分类列表
        List<CategoryVo> categoryVoList = categoryService.getLevelOneCategory();
        vo.setCategoryList(categoryVoList);
        //3.封装畅销TOP20商品列表
        List<ProductSkuVo> productSkuList = productSkuService.selectTopSale();
        vo.setProductSkuList(productSkuList);
        //4.响应VO
        return AjaxResult.success(vo);
    }



    @Operation(summary = "查询所有分类")
    @GetMapping("/category")
    public AjaxResult categoryList() {
        List<CategoryVo> categoryVoList = categoryService.tree();
        return AjaxResult.success(categoryVoList);
    }

    @Operation(summary = "分页条件查询商品列表")
    @GetMapping("/skuList/{pageNum}/{pageSize}")
    public TableDataInfo skulist(@PathVariable("pageNum") Integer pageNum,
                                 @PathVariable("pageSize") Integer pageSize,
                                 SkuQuery skuQuery){
        //1.开始分页
        PageHelper.startPage(pageNum,pageSize);
        //2.根据条件查sku列表
        List<ProductSkuVo> list= productSkuService.getskulist(skuQuery);
        return getDataTable(list);
    }
    @Autowired
    private BrandService brandService;
    @Operation(summary = "获取全部品牌")
    @GetMapping("/brand")
    public AjaxResult brandlist(){
        List<Brand> list = brandService.list();
        return AjaxResult.success(list);
    }

    @Autowired
    private SkuStockService skuStockService;
    @Autowired
    private ProductService productService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Operation(summary = "封装sku所需详情页信息")
    @GetMapping("item/{skuId}")
    public AjaxResult item(@PathVariable("skuId") Long skuId){
        //防止不存在的商品恶意访问造成缓存穿透
        Boolean bit = redisTemplate.opsForValue().getBit("product:sku:data", skuId);
        if (!bit){
            throw new RuntimeException("访问的商品不存在");
        }
        //1先创建一个itemvo对象为对象赋值
        ItemVo itemVo = new ItemVo();
        //2为对象属性赋值
        //2.1为producsku赋值
        CompletableFuture<Long> skuCompletableFuture = CompletableFuture.supplyAsync(() -> {
            ProductSku skuinfo = productSkuService.getinfo(skuId);
            itemVo.setProductSku(skuinfo);
            Long productId = skuinfo.getProductId();
            return productId;
        }, threadPoolExecutor);
        //2.2为sku价格赋值
        itemVo.setSkuPrice(productSkuService.getskuprice(skuId));
        //2.3查sku库存
        itemVo.setSkuStock(skuStockService.getskustock(skuId));
        CompletableFuture<Void> imageCompletableFuture = skuCompletableFuture.thenAcceptAsync(productId -> {
            //2.4查轮播图列表
            Product product = productService.getById(productId);
            if (product != null && StringUtils.isNoneBlank(product.getSliderUrls())) {
                String sliderUrls = product.getSliderUrls();
                String[] split = sliderUrls.split(",");
                itemVo.setSliderUrlList(split);
            }
            //2.5查商品详情图片列表
            ProductDetails productDetails = productDetailsService.getOne(
                    new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, productId)
            );
            if (productDetails != null && StringUtils.isNoneBlank(productDetails.getImageUrls())) {
                String imageUrls = productDetails.getImageUrls();
                String[] split = imageUrls.split(",");
                itemVo.setDetailsImageUrlList(split);
            }
            //2.6查询规格信息向用户展示,参数在商品表中就可以看到
            String specValue = product.getSpecValue();
            if (StringUtils.isNoneBlank(specValue)) {
                JSONArray jsonArray = JSON.parseArray(specValue);
                itemVo.setSpecValueList(jsonArray);
            }
            //2.7封装商品规格参数跟skuid映射关系map
            itemVo.setSkuSpecValueMap(productSkuService.getskuspecvalue(productId));
        }, threadPoolExecutor);
        //等待线程全部完成
        CompletableFuture.allOf(skuCompletableFuture,imageCompletableFuture).join();
        return success(itemVo);

    }
}
